<template>
  <div class="app-container">

    <el-form size="mini" style="margin-top: 18px" :inline="true">
      <el-form-item>
        <el-input v-model="tableQuery.name" placeholder="课程名称" style="width: 200px;" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-plus" @click="add()">
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table class="fill-main" size="mini" v-loading="tableLoading" :data="tableData" border fit highlight-current-row
      style="width: 100%">
      <template v-for="(item,index) of columnList">
        <el-table-column v-if="item.type!='rangeTime'" :key="index" :width="item.width" :min-width="item.minWidth"
          align="center" :label="item.label" :prop="item.prop">
          <template v-slot="{row}">
            <span v-if="['text','textarea','date'].indexOf(item.type)>=0">{{ row[item.prop] }}</span>
            <span v-else-if="item.type=='select'">{{value2label(item.options,row[item.prop])}}</span>
            <img width="30" height="30" v-if="item.type=='image'" :src="row[item.prop]" />
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" width="180px" fixed="right">
        <template v-slot="{row}">
          <span>
            <el-button size="mini" type="success" icon="el-icon-edit" @click="edit(row)">编辑</el-button>
            <el-popconfirm @confirm="()=>remove(row)" style="margin-left:10px" icon-color="red" title="确定要删除吗">
              <template v-slot:reference>
                <el-button :loading="row.removeLoading" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination small @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="tableQuery.page"
      :page-sizes="[5, 10, 20, 50]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <el-dialog :title="isAdd?'新增':'编辑'" :visible="dialogVisible" @update:visible="cancel" width="600px">
      <el-form :model="formData" ref="ruleForm" size="mini" label-width="85px">
        <template v-for="(item,index) of columnList">
          <el-form-item v-if="item.type!='time'" :key="index" :label="item.label+':'" :prop="item.prop" :rules="item.rules?item.rules:[]">
            <el-input v-if="item.type=='text'" v-model="formData[item.prop]"></el-input>
            <el-input v-else-if="item.type=='textarea'" type="textarea" v-model="formData[item.prop]"></el-input>
            <el-time-picker v-else-if="item.type=='date'"  v-model="formData[item.prop]" value-format="HH:mm:ss" style="width: 475px">
            </el-time-picker>
            <!--<el-upload v-else-if="item.type=='image'" action="" class="avatar-uploader" :http-request="(param)=>{handleRequest(param,item.prop)}"
              :show-file-list="false" drag>
              <img v-if="formData[item.prop]" :src="formData[item.prop]" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload> //上传图片的用这个

            <el-select v-else-if="item.type=='select'" v-model="formData[item.prop]" placeholder="" style="width: 475px">
              <el-option v-for="(item,index) in item.options" :key="index" :label="item.label" :value="item.value" />
            </el-select>//需要选择器的用这个

            <el-time-picker v-else-if="item.type=='rangeTime'" is-range v-model="formData[item.prop]" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" value-format="HH:mm:ss" style="width: 475px">
            </el-time-picker> //需要时间选择器的用这个--> 

          </el-form-item>
        </template>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button size="mini" @click="cancel()">取 消</el-button>
          <el-button :loading="submitLoading" size="mini" type="primary" @click="submit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/* import {
  addExpert,
  delExpert,
  updExpert,
  divFindExpert,
  divGetNameExpert
} from "/src/api/expertData";
import { upload } from "/src/api/common";
import { setTimeout } from "timers";
import { Promise } from "q";*/

const columnList = [
  {
    label: "课程名称",
    type: "text",
    prop: "name",
    width: 200,
    rules: [{ required: true, message: "请输入姓名", trigger: "blur" }]
  },
  {
    label: "描述",
    type: "textarea",
    prop: "area",
    width: 450,
    rules: [{ required: true, message: "请输入课程描述", trigger: "blur" }]
  },
  {
    label: "学期",
    type: "date",
    prop: "time",
    width: 300,
    rules: [{ required: true, message: "请输入学期", trigger: "blur" }]
  },
  /* {
    label: "性别",
    type: "select",
    options: [
      {
        label: "男",
        value: 1
      },
      {
        label: "女",
        value: 2
      }
    ],
    prop: "sex",
    width: 60,
    rules: [{ required: true, message: "请选择性别", trigger: "change" }]
  },
  {
    label: "在线时间",
    type: "rangeTime",
    prop: "time",
    width: 100,
    rules: [{ required: true, message: "请选择在线时间", trigger: "change" }]
  },
  {
    label: "在线开始时间",
    type: "time",
    prop: "start_time",
    width: 100,
    rules: [
      { required: true, message: "请选择在线开始时间", trigger: "change" }
    ]
  },
  {
    label: "在线结束时间",
    type: "time",
    prop: "end_time",
    width: 100,
    rules: [
      { required: true, message: "请选择在线结束时间", trigger: "change" }
    ]
  },
  {
    label: "联系方式",
    type: "text",
    prop: "telephone",
    width: 120,
    rules: [
      {
        required: true,
        message: "请输入正确的联系方式",
        pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
        trigger: "blur"
      }
    ]
  },
  {
    label: "职称",
    type: "text",
    prop: "job",
    width: 150,
    rules: [{ required: true, message: "请输入职称", trigger: "blur" }]
  },
  {
    label: "工作单位",
    type: "text",
    prop: "workplace",
    width: 200,
    rules: [{ required: true, message: "请输入工作单位", trigger: "blur" }]
  },

  {
    label: "个人简介",
    type: "textarea",
    prop: "introduction",
    minWidth: 200,
    rules: [{ required: true, message: "请输入个人简介", trigger: "blur" }]
  }*/
];

export default {
  name: "expertData",
  data() {
    return {
      dialogVisible: false,
      columnList,
      isAdd: true,
      formData: {},
      tableData: [{
          "name":"111",
          "area":"222",
          "time":"2021-2"
      }],
      tableLoading: false,
      tableQuery: { page: 1, size: 10, name: "" },
      total: 100,
      submitLoading: false,
      file: {}
    };
  },
  mounted() {
    // this.getTableData();
  },
  methods: {
    // 搜索
    search() {
      this.getTableData();
    },
    // 获取列表
    getTableData() {
      this.tableLoading = true;
      divGetNameExpert(this.tableQuery)
        .then(res => {
          res.obj.forEach(item => {
            item.removeLoading = false;
          });
          this.tableData = res.obj;
          this.total = res.maxCount;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 新增
    add() {
      this.isAdd = true;
      this.dialogVisible = true;
    },
    // 变换每页数据数（5，10...）
    handleSizeChange(size) {
      this.tableQuery.size = size;
      this.tableQuery.page = 1;
    },
    // 进入制定页
    handleCurrentChange(page) {
      this.tableQuery.page = page;
    },
    // 编辑
    edit(row) {
      row.time = [];
      row.time[0] = row.start_time;
      row.time[1] = row.end_time;
      this.isAdd = false;
      this.dialogVisible = true;
      this.formData = JSON.parse(JSON.stringify(row));
    },
    // 删除
    remove(row) {
      row.removeLoading = true;
      delExpert({ id: row.id })
        .then(res => {
          console.log(res);
          this.$message.success("删除成功");
        })
        .finally(() => {
          this.getTableData();
        });
    },
    // 提交请求的格式验证
    handleRequest(param, key) {
      this.file[key] = param.file;

      //文件是否为图片
      if (this.file[key].type.indexOf("image") < 0) {
        this.$message.warning("只能上传图片");
        return;
      }
      //图片不能大于2M
      if (this.file[key].size > 1024 * 1024 * 2) {
        this.$message.warning("图片不能大于2M");
        return;
      }

      // 回显
      this.$set(this.formData, key, window.URL.createObjectURL(this.file[key]));
      //手动触发验证
      this.$refs.ruleForm.validateField(key);
    },
    // 取消
    cancel() {
      this.dialogVisible = false;
      this.formData = {};
      this.$refs.ruleForm.resetFields();
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.formData.start_time = this.formData.time[0];
          this.formData.end_time = this.formData.time[1];
          Promise.all(
            Object.values(this.file).map(file =>
              upload(this.obj2formData({ img: file }))
            )
          )
            .then(res => {
              Object.keys(this.file).forEach((key, index) => {
                this.formData[key] = res[index].obj;
              });
              this.file = {};
              if (this.isAdd) {
                addExpert(this.obj2formData(this.formData))
                  .then(res => {
                    console.log(res);
                    this.$message.success("新增成功");
                    this.getTableData();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.cancel();
                  });
              } else {
                console.log(this.formData);
                updExpert(this.obj2formData(this.formData))
                  .then(res => {
                    console.log(res);
                    this.$message.success("修改成功");
                    this.getTableData();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.cancel();
                  });
              }
            })
            .catch(() => {
              this.submitLoading = false;
              this.cancel();
            });
        }
      });
    },
    obj2formData(obj) {
      let formData = new FormData();
      for (let key in obj) {
        formData.append(key, obj[key]);
      }
      return formData;
    },
    value2label(options, value) {
      for (let item of options) {
        if (item.value == value) {
          return item.label;
        }
      }
      return value;
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .el-pagination {
    margin-top: 20px;

    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  .el-pagination .el-select {
    position: relative;
    top: -3px;
  }
  .avatar-uploader .el-upload {
    width: 80px;
    height: 80px;
    /* border: 1px dashed #d9d9d9; */
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload-dragger {
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
  }
}
</style>

